package ie.three.webtexts;

import ie.three.webtexts.api.HttpAuthCredentials;
import ie.three.webtexts.api.RESTComponent;
import ie.three.webtexts.api.json.JSONInspector;
import ie.three.webtexts.base.WebtextBaseActivity;
import ie.three.webtexts.notification.Notify;

import java.text.MessageFormat;

import org.json.JSONObject;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

public class WebtextLoginActivity extends WebtextBaseActivity {

	ProgressDialog progressDialog;

	public Boolean hasStoredCredentials = false;
	public Context c;
	public int waitTime = 300;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// clearPrefs();
		Log.i(TAG, "Started");
		setContentView(R.layout.login_view);
		
		// TODO - initialise form with stored credentials if available. 
		
	}

	private class LoginTask extends AsyncTask<String, Void, JSONObject> {
		Context ctx = null;
		HttpAuthCredentials h = null;

		public LoginTask(Context c, HttpAuthCredentials httpauth) {
			this.ctx = c;
			this.h = httpauth;
		}

		@Override
		protected JSONObject doInBackground(String... params) {
			JSONObject j = new JSONObject();

			try {
				RESTComponent r = new RESTComponent();
				String login_url = MessageFormat.format(
						r.getAPIPropertyValue("api.get_account"), "", h.getMsisdn());
				Log.i(TAG, "Requesting: " + login_url);
				String response = r.getHttpResponse(login_url, h);
				if (!response.equals("")) {
					j = new JSONObject(response);
				}

				// Returns JSON Object
			} catch (Exception e) {
				Log.e(TAG, "Response: " + e.toString());
			}

			return j;
		}

		@Override
		protected void onPreExecute() {
			showDialog(LOGIN_DIALOG);
		}

		@Override
		protected void onPostExecute(JSONObject result) {
			// return result;
			Log.i(TAG, result.toString());
			dismissDialog(LOGIN_DIALOG);

			Boolean authenticated = false;
			try {
				JSONInspector ji = new JSONInspector();
				int statusCode = ji.inspect(result);
				Log.i(TAG, "Status Code: " + statusCode);

				Notify n = new Notify();

				switch (statusCode) {
				case 401:
					n.showValidationError("Invalid login details", c);
					break;
				case 408:
					n.showValidationError("The connection timed out", c);
					break;
				case 700:
					n.showValidationError(
							"Unable to access Webtext at this time, please try later.",
							c);
					break;
				case 200:
					authenticated = true;
					break;
				default:
					break;
				}

			} catch (Exception je) {
				je.printStackTrace();
			}
			Log.i(TAG, "Authenticated: " + authenticated);
			if (authenticated) {
				int r = 0;
				try {
					r = result.getInt("remainingAllowance");
				} catch (Exception e) {
					e.printStackTrace();
				}
				/* Store credentials for later user */
				// TODO determine whether checkbox was ticked and store credentials
				Log.i(TAG, "Storing credentials: " + h.toString());
				storeCredentials(h);

				Intent i = new Intent(c, WebtextSendActivity.class);
				i.putExtra("remainingAllowance", r);
				i.putExtra("msisdn", h.getMsisdn());
				i.putExtra("pin", h.getPin());
				// Show toast notification on first login only. 
				i.putExtra("showLoginSuccess", true);
				
				startActivity(i);
				finish();
			}
		}
	}

	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case LOGIN_DIALOG:
			progressDialog = new ProgressDialog(WebtextLoginActivity.this);
			progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressDialog.setMessage("Logging in"
					+ (hasStoredCredentials ? " with previously saved settings"
							: "") + ", please be patient...");
			return progressDialog;
		default:
			return null;
		}
	}

	public void authenticate(View view) {
		Notify notify = new Notify();

		EditText msisdn = (EditText) findViewById(R.id.username);
		EditText pin = (EditText) findViewById(R.id.password);

		Log.i(TAG, "MSISDN set to " + msisdn.getText().toString());
		Log.i(TAG, "PIN set to " + pin.getText().toString());

		Boolean valid = !pin.getText().toString().trim().isEmpty()
				&& !msisdn.getText().toString().trim().isEmpty();
		// Added this in to save myself having to manually enter pin and msisdn,
		// just click button.
		// valid = true;

		if (valid) {
			c = this;
			LoginTask l = new LoginTask(c, new HttpAuthCredentials(msisdn
					.getText().toString(), pin.getText().toString()));
			l.execute();
		} else {
			notify.showValidationError(
					getString(R.string.login_validation_error), this);
		}
	}

}